import React, { useRef } from 'react'
import { message, Modal } from 'antd'
import PropTypes from 'prop-types'
import { CaseContext } from '../../../context'
import { addAgentRequest } from '../ajax/agentAjax'
import { awaitWrap } from '@js/tool'
import ModalForm from './ModalForm'

// 获取默认值
function getInitialValues (caseid, type, dictionaries, partyList, agents) {
  const licenseTypeList = (dictionaries['自然人证件类型'] || []).map(li => li.title)
  const freePartyList = getFreeParty(partyList, agents, type)
  return {
    caseid,
    type,
    name: undefined, // 全称姓名
    license_type: licenseTypeList[0], // 证照类型
    license: '', // 证照号
    structure: '', // 所在单位
    address: '', // 详细地址
    mobile: '', // 手机号
    email: '', // 邮箱
    tel: '', // 其他联系方式
    party: freePartyList, // 被代理的当事人
    partyIndex: freePartyList.map(f => f.partyid),
    party_type: type // 代理当事人类型
  }
}

// 获取未被代理的当事人
function getFreeParty (partyList, agents, type) {
  const set = new Set()
  const res = []
  agents.forEach(v => {
    v.party.forEach(p => {
      set.add(p.partyid)
    })
  })
  partyList.forEach(p => {
    if (!set.has(p.id)) {
      res.push({
        scope_type: '', // 代理类型
        scope: '', // 代理权限
        type, // 当事人类型
        partyid: p.id
      })
    }
  })
  return res
}

// 表单回调，提交数据
async function onFinish (data, caseid, list, callback, hide) {
  data.caseid = caseid
  delete data.partyIndex
  if (data.subject_type === '自然人') {
    data.legal = ''
  }
  const h = message.loading('提交中', 120)
  const [e, d] = await awaitWrap(addAgentRequest(data))
  h()
  if (e) {
    return message.warning(e.message)
  }
  const l = list ? [...list] : []
  l.push(d)
  callback(l)
  hide()
}

// 获取当事人列表
function getPartyList (caseFormRef, type) {
  if (!caseFormRef) {
    return []
  }
  const c = caseFormRef.current
  if (!c) {
    return []
  }
  const m = {
    申请人: 'applicants',
    被申请人: 'respondents'
  }
  return c.getFieldValue(m[type]) || []
}

function Main ({ visible, type, hide, value, onChange, caseFormRef }) {
  const formRef = useRef(null)
  const partyList = getPartyList(caseFormRef, type)
  return (
    <Modal
      width='700px'
      title={`新增${type}代理人`}
      open={visible}
      onOk={() => formRef.current.submit()}
      onCancel={hide}
      maskClosable={false}
      destroyOnClose
    >
      <CaseContext.Consumer>
        {({ id, dictionaries, isPre }) => (
          <ModalForm ref={formRef} isPre={isPre} type={type} caseFormRef={caseFormRef} partyList={partyList} initialValues={getInitialValues(id, type, dictionaries, partyList, value)} dictionaries={dictionaries} onFinish={d => onFinish(d, id, value, onChange, hide)} />
        )}
      </CaseContext.Consumer>
    </Modal>
  )
}

Main.propTypes = {
  visible: PropTypes.bool,
  type: PropTypes.string,
  hide: PropTypes.func,
  value: PropTypes.array,
  onChange: PropTypes.func,
  caseFormRef: PropTypes.object
}

Main.defaultProps = {
  visible: false,
  type: '',
  hide: () => {},
  value: [],
  onChange: () => {},
  caseFormRef: null
}

export default Main
